<template>
  <div class="promotions-container">
    <!-- 搜索和操作栏 -->
    <div class="action-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索活动名称"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchType"
            placeholder="活动类型"
            clearable
            style="width: 100%;"
            @change="handleSearch"
          >
            <el-option label="全部" :value="null" />
            <el-option label="满减" value="discount" />
            <el-option label="折扣" value="percent" />
            <el-option label="秒杀" value="flash" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchStatus"
            placeholder="活动状态"
            clearable
            style="width: 100%;"
            @change="handleSearch"
          >
            <el-option label="全部" :value="null" />
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已结束" :value="2" />
            <el-option label="已取消" :value="3" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-button type="primary" @click="openAddDialog">
            <el-icon><Plus /></el-icon> 创建活动
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 活动列表 -->
    <el-table
      :data="promotionList"
      style="width: 100%"
      border
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="活动名称" />
      <el-table-column prop="type" label="活动类型" width="120">
        <template #default="scope">
          <el-tag :type="getTypeTag(scope.row.type)">
            {{ getTypeName(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row.status)">
            {{ getStatusName(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deletePromotion(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑活动对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '创建活动' : '编辑活动'"
      v-model="dialogVisible"
      width="50%"
    >
      <el-form :model="promotionForm" :rules="rules" label-width="100px" ref="promotionFormRef">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="promotionForm.name" />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="promotionForm.type" placeholder="请选择活动类型" style="width: 100%;">
            <el-option label="满减" value="discount" />
            <el-option label="折扣" value="percent" />
            <el-option label="秒杀" value="flash" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-select v-model="promotionForm.status" placeholder="请选择活动状态" style="width: 100%;">
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已结束" :value="2" />
            <el-option label="已取消" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="活动规则">
          <div v-if="promotionForm.type === 'discount'">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="满" label-width="30px">
                  <el-input-number v-model="discountRules.condition" :min="0" :step="10" controls-position="right" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="减" label-width="30px">
                  <el-input-number v-model="discountRules.discount" :min="0" :step="5" controls-position="right" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
            <div class="form-tip">满减规则：满 {{ discountRules.condition }} 元减 {{ discountRules.discount }} 元</div>
          </div>
          <div v-else-if="promotionForm.type === 'percent'">
            <el-form-item label="折扣">
              <el-input-number
                v-model="percentRules.displayPercent"
                :min="1"
                :max="9.9"
                :step="0.1"
                :precision="1"
                controls-position="right"
                style="width: 100%;"
                @change="handlePercentChange"
              />
            </el-form-item>
            <div class="form-tip">折扣规则：打 {{ percentRules.displayPercent }} 折</div>
          </div>
          <div v-else-if="promotionForm.type === 'flash'">
            <el-form-item label="秒杀价">
              <el-input-number v-model="flashRules.price" :min="0" :step="10" controls-position="right" style="width: 100%;" />
            </el-form-item>
            <div class="form-tip">秒杀规则：秒杀价 {{ flashRules.price }} 元</div>
          </div>
        </el-form-item>
        <el-form-item label="关联商品">
          <div class="product-select-container">
            <el-select
              v-model="promotionForm.productIds"
              multiple
              filterable
              placeholder="请选择关联商品"
              style="width: 100%;"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="`${item.name} (${getCategoryName(item.categoryId)})`"
                :value="item.id"
              />
            </el-select>
            <el-button
              type="primary"
              plain
              size="small"
              @click="clearSelectedProducts"
              style="margin-left: 10px;"
            >
              一键清空
            </el-button>
          </div>
          <div class="form-tip">不选择商品则表示全场参与活动</div>
        </el-form-item>
        <el-form-item label="活动描述">
          <el-input v-model="promotionForm.description" type="textarea" rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePromotion">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { getPromotions, getPromotionDetail, addPromotion, updatePromotion, updatePromotionStatus, deletePromotion as apiDeletePromotion, getProducts } from '@/api/merchant'
import { getAllCategories } from '@/api/category'

// 定义API响应接口
interface ApiResponse<T = any> {
  code: number;
  data: T;
  message: string;
}

// 定义接口类型
interface Product {
  id: number;
  name: string;
  categoryId: number;
}

interface Category {
  id: number;
  name: string;
}

interface Promotion {
  id: number;
  name: string;
  type: string;
  startTime: string;
  endTime: string;
  status: number;
  description?: string;
  rules?: string;
}

// 活动列表
const promotionList = ref<Promotion[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const searchType = ref(null)
const searchStatus = ref(null)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const promotionForm = reactive({
  id: 0,
  name: '',
  type: 'discount',
  description: '',
  rules: '',
  productIds: [] as number[],
  status: 0 // 默认为未开始状态
})



// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择活动状态', trigger: 'change' }
  ]
}

// 商品选项
const productOptions = ref<Product[]>([])
// 分类列表
const categoryList = ref<Category[]>([])

// 活动规则相关
const discountRules = reactive({
  condition: 100,
  discount: 20
})

const percentRules = reactive({
  percent: 0.8,
  displayPercent: 8.0
})

const flashRules = reactive({
  price: 99.9
})

// 处理折扣率变化
const handlePercentChange = (val: number) => {
  // 将显示的折扣值（例如8.5折）转换为内部存储的百分比值（0.85）
  percentRules.percent = val / 10
}



// 根据活动类型更新规则表单
const updateRulesByType = (type: string, rulesStr: string) => {
  try {
    if (!rulesStr) {
      // 设置默认值
      if (type === 'discount') {
        Object.assign(discountRules, { condition: 100, discount: 20 })
      } else if (type === 'percent') {
        Object.assign(percentRules, { percent: 0.8 })
      } else if (type === 'flash') {
        Object.assign(flashRules, { price: 99.9 })
      }
      return
    }

    const rules = JSON.parse(rulesStr)

    if (type === 'discount' && rules.condition !== undefined && rules.discount !== undefined) {
      Object.assign(discountRules, {
        condition: Number(rules.condition),
        discount: Number(rules.discount)
      })
    } else if (type === 'percent' && rules.percent !== undefined) {
      const percent = Number(rules.percent)
      Object.assign(percentRules, {
        percent: percent,
        displayPercent: Number((percent * 10).toFixed(1))
      })
    } else if (type === 'flash' && rules.price !== undefined) {
      Object.assign(flashRules, {
        price: Number(rules.price)
      })
    }
  } catch (error) {
    console.error('解析活动规则失败:', error)
    // 设置默认值
    if (type === 'discount') {
      Object.assign(discountRules, { condition: 100, discount: 20 })
    } else if (type === 'percent') {
      Object.assign(percentRules, { percent: 0.8, displayPercent: 8.0 })
    } else if (type === 'flash') {
      Object.assign(flashRules, { price: 99.9 })
    }
  }
}

// 监听活动类型变化，更新规则表单
watch(() => promotionForm.type, (newType) => {
  updateRulesByType(newType, promotionForm.rules)
})

// 监听规则变化，更新promotionForm.rules
watch([discountRules, percentRules, flashRules], () => {
  if (promotionForm.type === 'discount') {
    promotionForm.rules = JSON.stringify({
      condition: discountRules.condition,
      discount: discountRules.discount
    })
  } else if (promotionForm.type === 'percent') {
    promotionForm.rules = JSON.stringify({
      percent: percentRules.percent
    })
  } else if (promotionForm.type === 'flash') {
    promotionForm.rules = JSON.stringify({
      price: flashRules.price
    })
  }
}, { deep: true })

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const response = await getAllCategories() as unknown as ApiResponse
    if (response.code === 200) {
      categoryList.value = response.data
      console.log('获取到的分类列表:', categoryList.value)
    } else {
      console.error('获取分类列表失败:', response)
      ElMessage.error('获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 获取商品列表
const fetchProductOptions = async () => {
  try {
    const response = await getProducts({ pageSize: 100 }) as unknown as ApiResponse
    console.log('获取商品列表响应:', response)

    if (response.code === 200 && response.data && response.data.records) {
      productOptions.value = response.data.records.map((item: any) => ({
        id: item.id,
        name: item.name,
        categoryId: item.categoryId
      }))
      console.log('商品选项:', productOptions.value)
    } else {
      console.error('获取商品列表失败:', response)
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
  }
}

// 获取分类名称
const getCategoryName = (categoryId: number | null) => {
  if (!categoryId) return '未分类'
  const category = categoryList.value.find(item => item.id === categoryId)
  return category ? category.name : '未知分类'
}



// 获取活动类型名称
const getTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    discount: '满减',
    percent: '折扣',
    flash: '秒杀'
  }
  return typeMap[type] || type
}

// 获取活动类型标签样式
const getTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    discount: 'success',
    percent: 'warning',
    flash: 'danger'
  }
  return typeMap[type] || ''
}

// 获取活动状态名称
const getStatusName = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '未开始',
    1: '进行中',
    2: '已结束',
    3: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取活动状态标签样式
const getStatusTag = (status: number) => {
  const statusMap: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return statusMap[status] || ''
}

// 打开添加对话框
const openAddDialog = () => {
  dialogType.value = 'add'

  // 设置默认活动类型
  const defaultType = 'discount'

  // 初始化默认规则
  let defaultRules = ''

  if (defaultType === 'discount') {
    defaultRules = JSON.stringify({
      condition: 100,
      discount: 20
    })
  } else if (defaultType === 'percent') {
    defaultRules = JSON.stringify({
      percent: 0.8
    })
  } else if (defaultType === 'flash') {
    defaultRules = JSON.stringify({
      price: 99.9
    })
  }

  Object.assign(promotionForm, {
    id: 0,
    name: '',
    type: defaultType,
    description: '',
    rules: defaultRules,
    productIds: [],
    status: 0 // 默认为未开始状态
  })

  // 更新规则表单
  updateRulesByType(defaultType, defaultRules)

  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = async (row: any) => {
  dialogType.value = 'edit'
  let loadingInstance: any = null; // Initialize loadingInstance
  try {
    loadingInstance = ElLoading.service({ fullscreen: true, text: '加载中...' })
    console.log('获取活动详情，ID:', row.id)

    // 获取活动详情
    const response = await getPromotionDetail(row.id) as unknown as ApiResponse
    console.log('获取活动详情响应:', response)

    if (response.code === 200 && response.data) {
      const promotionDetail = response.data.promotion || row
      const productIds = response.data.productIds || []

      console.log('活动详情:', promotionDetail)
      console.log('关联商品IDs:', productIds)

      const type = promotionDetail.type || 'discount'
      const rulesStr = promotionDetail.rules || ''

      Object.assign(promotionForm, {
        id: promotionDetail.id,
        name: promotionDetail.name,
        type: type,
        description: promotionDetail.description || '',
        rules: rulesStr,
        productIds: productIds,
        status: promotionDetail.status !== undefined ? promotionDetail.status : 0
      })

      updateRulesByType(type, rulesStr)
      console.log('设置表单数据:', promotionForm)
      dialogVisible.value = true
    } else {
      // ... API调用失败时的处理逻辑 (保持不变) ...
      console.warn('获取活动详情失败，使用表格行数据:', row)

      const type = row.type || 'discount'
      const rulesStr = row.rules || ''

      Object.assign(promotionForm, {
        id: row.id,
        name: row.name,
        type: type,
        description: row.description || '',
        rules: rulesStr,
        productIds: [],
        status: row.status !== undefined ? row.status : 0
      })

      updateRulesByType(type, rulesStr)
      dialogVisible.value = true
      ElMessage.warning('获取完整活动详情失败，部分数据可能不完整')
    }

    loadingInstance.close()
  } catch (error) {
    console.error('获取活动详情处理失败:', error)
    ElMessage.error('获取活动详情失败')
    if (loadingInstance) { // Check if loadingInstance exists before closing
        loadingInstance.close();
    }
  }
}

// 保存活动
const savePromotion = async () => {
  // 基础表单验证
  if (!promotionForm.name) {
    ElMessage.warning('请输入活动名称')
    return
  }
  if (!promotionForm.type) {
    ElMessage.warning('请选择活动类型')
    return
  }

  let loadingInstance: any = null; // Initialize loadingInstance
  try {
    loadingInstance = ElLoading.service({ fullscreen: true, text: '保存中...' })

    // 基础表单验证 - 检查状态
    if (promotionForm.status === undefined) {
      ElMessage.warning('请选择活动状态')
      loadingInstance.close()
      return
    }

    // 保存原始状态，用于检测状态是否变化
    let originalStatus = -1;
    if (dialogType.value === 'edit') {
      // 获取当前列表中的活动状态
      const currentPromotion = promotionList.value.find(p => p.id === promotionForm.id);
      if (currentPromotion) {
        originalStatus = currentPromotion.status;
      }
    }

    // 构建发送给后端的数据
    const promotionData: any = {
      name: promotionForm.name,
      type: promotionForm.type,
      description: promotionForm.description || '',
      rules: promotionForm.rules || '',
      productIds: promotionForm.productIds || [],
      // 始终包含状态字段，无论是添加还是编辑模式
      status: promotionForm.status
    }

    if (dialogType.value === 'edit') {
      promotionData.id = promotionForm.id
    }

    console.log('保存活动数据:', promotionData)

    let response: ApiResponse;
    if (dialogType.value === 'add') {
      console.log('添加新活动')
      response = await addPromotion(promotionData) as unknown as ApiResponse
      console.log('添加活动响应:', response)

      if (response.code === 200 && promotionForm.status === 1) {
        // 如果是新添加的活动且状态为"进行中"，显示相应消息
        const newId = response.data.id;
        console.log('新活动ID:', newId, '，状态设置为进行中');
        ElMessage.success('活动已开始，商品价格已更新');
      }
    } else {
      console.log('编辑活动，ID:', promotionForm.id)
      response = await updatePromotion(promotionForm.id, promotionData) as unknown as ApiResponse
      console.log('编辑活动响应:', response)

      // 如果状态发生变化，显示相应的消息
      if (response.code === 200 && originalStatus !== promotionForm.status) {
        console.log('活动状态从', originalStatus, '变更为', promotionForm.status);

        // 状态已在主请求中更新，直接显示相应消息
        if (promotionForm.status === 1) {
          ElMessage.success('活动已开始，商品价格已更新');
        } else if (promotionForm.status === 2 || promotionForm.status === 3) {
          ElMessage.success('活动已' + (promotionForm.status === 2 ? '结束' : '取消') + '，商品价格已恢复');
        }
      }
    }

    if (response.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
        dialogVisible.value = false
        await fetchPromotionList()
    } else {
        console.error(`${dialogType.value === 'add' ? '添加' : '编辑'}活动失败，响应码:`, response.code)
        ElMessage.error(`${dialogType.value === 'add' ? '添加' : '编辑'}失败: ${response.message || '未知错误'}`)
    }

    loadingInstance.close()
  } catch (error) {
    console.error('保存活动处理失败:', error)
    ElMessage.error('保存活动失败，请检查网络连接或刷新页面重试')
    if (loadingInstance) { // Check if loadingInstance exists before closing
      loadingInstance.close()
    }
  }
}

// 删除活动
const deletePromotion = (row: any) => {
  ElMessageBox.confirm('确定要删除该活动吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      console.log('删除活动，ID:', row.id)
      const response = await apiDeletePromotion(row.id) as unknown as ApiResponse
      console.log('删除活动响应:', response)

      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchPromotionList()
      } else {
        console.error('删除活动失败，响应码:', response.code)
        ElMessage.error(`删除失败: ${response.message || '未知错误'}`)
      }
    } catch (error) {
      console.error('删除活动失败:', error)
      ElMessage.error('删除活动失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchPromotionList()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchPromotionList()
}

// 搜索活动
const handleSearch = () => {
  currentPage.value = 1
  fetchPromotionList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  searchType.value = null
  searchStatus.value = null
  currentPage.value = 1
  fetchPromotionList()
}

// 获取活动列表
const fetchPromotionList = async () => {
  loading.value = true
  try {
    console.log('开始获取促销活动列表，参数:', {
      keyword: searchKeyword.value,
      type: searchType.value,
      status: searchStatus.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })

    const response = await getPromotions({
      keyword: searchKeyword.value,
      type: searchType.value,
      status: searchStatus.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }) as unknown as ApiResponse

    console.log('获取促销活动列表响应:', response)

    // 检查响应数据结构
    console.log('响应数据结构:', response)

    if (response.code === 200) {
      if (response.data && response.data.records) {
        promotionList.value = response.data.records
        total.value = response.data.total
        console.log('促销活动列表数据:', promotionList.value)
      } else if (Array.isArray(response.data)) {
        // 如果直接返回数组
        promotionList.value = response.data
        total.value = response.data.length
        console.log('促销活动列表数据(数组):', promotionList.value)
      } else {
        console.error('响应数据结构不符合预期:', response.data)
        promotionList.value = []
        total.value = 0
      }
    } else {
      console.error('获取促销活动列表失败，响应码:', response.code)
      ElMessage.error(`获取促销活动列表失败: ${response.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('获取促销活动列表失败:', error)
    ElMessage.error('获取促销活动列表失败')
  } finally {
    loading.value = false
  }
}

// 清空已选择的商品
const clearSelectedProducts = () => {
  promotionForm.productIds = []
  ElMessage.success('已清空关联商品')
}

// 页面加载时获取活动列表、分类列表和商品选项
onMounted(() => {
  fetchCategoryList()
  fetchPromotionList()
  fetchProductOptions()
})
</script>

<style scoped>
.promotions-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.product-select-container {
  display: flex;
  align-items: center;
}
</style>
